#!/usr/bin/env ruby

# Copyright (c) 2010-2012 Microsoft Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#	http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

require 'rubygems'
require 'ruby-aws'
require 'optparse'

require './include/config'
require './include/proxy'
require './include/requester'

@config = MOS::Config.create
@mturk = Amazon::WebServices::MechanicalTurkRequester.new :Host => @config[:Server]

def extendHIT(hit_id)
	params = { }
	params[:MaxAssignmentsIncrement]      = @options[:assignmentinc] if @options[:assignmentinc] > 0
	params[:ExpirationIncrementInSeconds] = @options[:expirationinc] if @options[:expirationinc] > 0
	params[:HITId] = hit_id

	begin
		printf("Extending HIT with Id %s\n", hit_id)
		@mturk.ExtendHIT(params)
	rescue => e
		$stderr.printf("Error extending HIT with Id %s: %s\n", hit_id, e.message)
	end
end

@options = { }
optparse = OptionParser.new do |opts|
	opts.banner = "Usage: #{$0} [options]"
 
	@options[:quiet] = false
	opts.on( '-q', '--quiet', 'Do not print any messages (implies -f)' ) do
		@options[:quiet] = true
	end

	@options[:all] = false
	opts.on( '-a', '--all', 'Extend all HITs in account' ) do
		@options[:all] = true
	end

	@options[:force] = false
	opts.on( '-f', '--force', 'Do not ask for confirmation' ) do
		@options[:force] = true
	end

	@options[:assignmentinc] = 0
	opts.on( '--assignment-increment N', Integer,
			'Number of assignments by which to increment MaxAssignments' ) do |n|
		@options[:assignmentinc] = n
	end

	@options[:expirationinc] = 0
	opts.on( '--expiration-increment N', Integer,
			'Amount of time, in seconds, by which to increment the expiration date' ) do |n|
		@options[:expirationinc] = n
	end
 
	opts.on( '-h', '--help', 'Display this screen' ) do
		puts opts
		exit
	end

	opts.on_tail("")
	opts.on_tail("This script extends the number of assignments of expiration date of HITs.")
	opts.on_tail("It can operate on all HITs in the MTurk account, or only on HITs identified in given files.")
end

begin
	optparse.parse!
rescue OptionParser::ParseError => e
	$stderr.puts("Error parsing command-line arguments: " + e.message)
	$stderr.puts("Try '#{$0} --help' for more information.")
	exit
end

if @options[:expirationinc] == 0 && @options[:assignmentinc] == 0
	$stderr.puts("You must extend the expiration date or the number of assignments.")
	$stderr.puts("Try '#{$0} --help' for more information.")
	exit
end

if @options[:quiet]
	@options[:force] = true
	devnull = File.exist?('/dev/null') ? '/dev/null' : 'NUL'
	$stdout = File.new(devnull, 'w')
end

if !@options[:force]
	printf("Are you sure you want to extend all HITs? (y/n) ")
	response = STDIN.gets.chomp.downcase
	if response != 'y'
		printf("Exiting...\n")
		exit
	end
end

if @options[:all]
	hit_list = @mturk.collect_HITs
	hit_list.each { |hit| extendHIT(hit[:HITId]) }
else
	hit_list = Amazon::Util::DataReader.load(@config[:HITSuccessFile], :Tabular)
	hit_list.each { |hit| extendHIT(hit[:HITId]) }
end

